package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IDepartmentService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    // /department/list.do
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo) {
        System.out.println("当前登录用户是否有HR_MGR角色："
            + SecurityUtils.getSubject().hasRole("HR_MGR"));

        System.out.println("当前登录用户是否有employee:delete权限："
                + SecurityUtils.getSubject().isPermitted("employee:delete"));



        PageInfo<Department> pageInfo = departmentService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "department/list"; // /WEB-INF/views/department/list.jsp
    }

    @RequestMapping("/input")
    public String input(Model model, Long id) {
        if (id != null) {
            Department department = departmentService.select(id);
            model.addAttribute("department", department);
        }
        return "department/input";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Department dept) {
        try {
            if (dept.getId() != null) {
                departmentService.update(dept);
            } else {
                departmentService.insert(dept);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "操作失败");
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            if (id != null) {
                departmentService.delete(id);
                return new JsonResult();
            }
            return new JsonResult(false, "操作失败");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "操作失败");
        }
    }
}
